<template>
  <div class="logs-login">
    <com-search :form-item="searchConfig" :form-data="searchFormData" @search="handleComSearch" />
    <div class="table-container">
      <table-header
        v-model:columns="columns"
        table-id="systemUser"
        :buttons="['refresh', 'quickSearch', 'comSearch', 'colSetting']"
        role-prefix="system:user"
        @refresh="getLoginLogsList"
        @change="handleInputChange"
      />
      <table-base
        :columns="columns"
        :table-data="loginLogsList"
        :total="total"
        :page-index="searchParams.pageIndex"
        :page-size="searchParams.pageSize"
        :loading="loading"
        @page-change="handlePageChange"
      >
        <template #login-type="scope">
          <el-tag v-if="scope.row.loginType === loginTypeEnum.SUCCESS" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </template>
        <template #create-time="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </table-base>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue"
import { columns } from "./config/content.config"
import { searchConfig } from "./config/search.config"
import { loginTypeEnum } from "@/enums/logs"
import TableHeader from "@/components/base/TableHeader.vue"
import TableBase from "@/components/base/TableBase.vue"
import ComSearch from "@/components/base/ComSearch.vue"
import { getLoginLogsPage } from "@/api/logs"
import { showErrorToast } from "@/utils/toast"
import { formatDateTime } from "@/utils/format"

interface SearchFormData {
  key: string
  date: string
}

const loading = ref(false)
const total = ref(0)
const loginLogsList = ref<LoginLogsResponse[]>([])

const searchFormData = ref<SearchFormData>({
  key: "",
  date: ""
})

// 搜索参数
const searchParams = reactive<LoginLogsQueryRequest>({
  key: "",
  start: "",
  end: "",
  pageIndex: 1,
  pageSize: 10
})

const handlePageChange = (pageIndex: number, pageSize: number) => {
  searchParams.pageIndex = pageIndex
  searchParams.pageSize = pageSize
  getLoginLogsList()
}

const handleComSearch = (formData: SearchFormData) => {
  searchParams.key = formData.key
  searchParams.start = formData.date[0]
  searchParams.end = formData.date[1]
  doSearch()
}

const doSearch = () => {
  searchParams.pageIndex = 1
  getLoginLogsList()
}

const handleInputChange = (value: string) => {
  searchParams.key = value
  doSearch()
}

onMounted(() => {
  getLoginLogsList()
})

async function getLoginLogsList() {
  loading.value = true
  try {
    const res = await getLoginLogsPage(searchParams)
    if (res.data) {
      loginLogsList.value = res.data.list ?? []
      total.value = res.data.totalCount ?? 0
    }
  } catch (error: any) {
    showErrorToast(error.message)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
